package com.jt.ktdemo.ui.register

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.InputType
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.view.Window
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.jt.ktdemo.MyApplication
import com.jt.ktdemo.R
import com.jt.ktdemo.bean.BackBean
import com.jt.ktdemo.bean.LoginCallbackBean
import com.jt.ktdemo.bean.RegisterCallbackBean
import com.jt.ktdemo.databinding.RegisterBinding
import com.jt.ktdemo.http.HTTPAPI
import com.jt.ktdemo.ui.login.LoginActivity
import com.jt.ktdemo.ui.mian.MainActivity
import com.jt.ktdemo.utils.GsonUtils
import com.jt.ktdemo.utils.LogUtil
import com.jt.ktdemo.utils.SpUtils
import com.lzy.okgo.callback.StringCallback
import okhttp3.Call
import okhttp3.Response

class RegisterActivity : AppCompatActivity() {

    lateinit var binding: RegisterBinding
    var pwdPoint: Boolean = true
    var pwdAgainPoint: Boolean = true
    val sampleDrawables = intArrayOf(R.drawable.yanjing_xianshi_o, R.drawable.yanjing_yincang_o)
    private var firstEditText: Boolean = false
    private var secondEditText: Boolean = false
    private var forthEditText: Boolean = false
    private var fivethEditText: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        binding = DataBindingUtil.setContentView(this,R.layout.register)
        binding.activity = this
        findViewById<TextView>(R.id.tvModuleLogin).setOnClickListener {
            startActivity(Intent(this, LoginActivity().javaClass))
            finish()
        }

        //密码
        var ivModulePwd = findViewById<ImageView>(R.id.ivModulePwd)
        var etModulePwd = findViewById<EditText>(R.id.etModulePwd)

        ivModulePwd.setOnClickListener {
            if (pwdPoint) {
                pwdPoint = false
                ivModulePwd.setImageResource(sampleDrawables[0])
                etModulePwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            } else {
                pwdPoint = true
                ivModulePwd.setImageResource(sampleDrawables[1])
                etModulePwd.setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD)
            }
            etModulePwd.setSelection(etModulePwd.text.toString().length)
        }

        //确认密码
        var ivModulePwdAgain = findViewById<ImageView>(R.id.ivModulePwdAgain)
        var etModulePwdAgain = findViewById<EditText>(R.id.etModulePwdAgain)

        ivModulePwdAgain.setOnClickListener {
            if (pwdAgainPoint) {
                pwdAgainPoint = false
                ivModulePwdAgain.setImageResource(sampleDrawables[0])
                etModulePwdAgain.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            } else {
                pwdAgainPoint = true
                ivModulePwdAgain.setImageResource(sampleDrawables[1])
                etModulePwdAgain.setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD)
            }
            etModulePwdAgain.setSelection(etModulePwdAgain.text.toString().length)
        }

        var llModule: LinearLayout = findViewById(R.id.llModulePro)
        var etModuleName: EditText = findViewById(R.id.etModuleName)
        var etModuleEmail: EditText = findViewById(R.id.etModuleEmail)


        findViewById<Button>(R.id.btModuleRegister).setOnClickListener {

            firstEditText = !TextUtils.isEmpty(binding.etModuleName.text.toString().trim());
            secondEditText = !TextUtils.isEmpty(binding.etModuleEmail.text.toString().trim());
            forthEditText = !TextUtils.isEmpty(binding.etModulePwd.text.toString().trim());
            fivethEditText = !TextUtils.isEmpty(binding.etModulePwdAgain.text.toString().trim());

            LogUtil.e("firstEditText-->"+ firstEditText)
            LogUtil.e("secondEditText-->"+ secondEditText)
            LogUtil.e("forthEditText-->"+ forthEditText)
            LogUtil.e("fivethEditText-->"+ fivethEditText)
            if (firstEditText && secondEditText && forthEditText && fivethEditText) {
                var name: String = etModuleName.getText().toString().trim()
                var email: String = etModuleEmail.getText().toString().trim()
                var pwd: String = etModulePwd.getText().toString().trim()
                var pwdAgain: String = etModulePwdAgain.getText().toString().trim()

                //判断是否输入name,未输入则提示
                if (TextUtils.isEmpty(name)) {
                    showToast("Please enter your name")

                    //判断是否输入邮箱，未输入则提示
                } else if (TextUtils.isEmpty(email)) {
                    showToast("Please enter your email address")

                } else if (TextUtils.isEmpty(pwd)) {
                    showToast("please enter your PIN")

                    //判断二次密码是否输入，未输入则提示
                } else if (TextUtils.isEmpty(pwdAgain)) {
                    showToast("Please confirm your password")

                    //判断两次密码是否一致，不一致则提示
                } else if (!pwd.equals(pwdAgain)) {
                    showToast("Entered passwords differ")

                } else {
                    llModule.visibility = View.VISIBLE
                    toRegister(name, email, "", pwd, llModule)
                }
            }
        }

        binding.etModuleName.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                var inputStr = s.toString();
                firstEditText = !TextUtils.isEmpty(inputStr)
                LogUtil.e("firstEditText-->"+firstEditText)
                checkBoolean()
            }
        })

        binding.etModuleEmail.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                var inputStr = s.toString();
                secondEditText = !TextUtils.isEmpty(inputStr)
                LogUtil.e("secondEditText-->"+secondEditText)
                checkBoolean()
            }
        })

        binding.etModulePwd.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                var inputStr = s.toString();
                forthEditText = !TextUtils.isEmpty(inputStr)
                LogUtil.e("forthEditText-->"+forthEditText)
                checkBoolean()
            }
        })


        binding.etModulePwdAgain.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                var inputStr = s.toString();
                fivethEditText = !TextUtils.isEmpty(inputStr)
                LogUtil.e("fivethEditText-->"+fivethEditText)
                checkBoolean()
            }
        })
    }


    @SuppressLint("NewApi")
    fun checkBoolean() {
        LogUtil.e("firstEditText-->"+ firstEditText)
        LogUtil.e("secondEditText-->"+ secondEditText)
        LogUtil.e("forthEditText-->"+ forthEditText)
        LogUtil.e("fivethEditText-->"+ fivethEditText)

        firstEditText = !TextUtils.isEmpty(binding.etModuleName.text.toString().trim());
        secondEditText = !TextUtils.isEmpty(binding.etModuleEmail.text.toString().trim());
        forthEditText = !TextUtils.isEmpty(binding.etModulePwd.text.toString().trim());
        fivethEditText = !TextUtils.isEmpty(binding.etModulePwdAgain.text.toString().trim());

        if (firstEditText && secondEditText && forthEditText && fivethEditText) {
            binding.btModuleRegister.setBackgroundResource(R.drawable.draw_module_login_bg)
        } else {
            binding.btModuleRegister.setBackgroundResource(R.drawable.draw_module_login_bg_selected)
        }
    }

    /**
     * 显示弹窗
     */
    fun showToast(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }

    fun toRegister(
        name: String,
        email: String,
        phoneNumber: String,
        pwd: String,
        llModule: LinearLayout
    ) {
        HTTPAPI.toRegister(name, pwd, email, phoneNumber, object : StringCallback() {
            override fun onSuccess(t: String?, call: Call?, response: Response?) {
                llModule.visibility = View.GONE
                LogUtil.e("注册结果$t")
                var bean: BackBean =
                    GsonUtils.parse(t.toString(), BackBean::class.java)
                if (!bean.IsError) {

                    //姓名存储
                    SpUtils.put("module_name", name)
                    //邮箱存储
                    SpUtils.put("module_email", email)
                    //密码存储
                    SpUtils.put("module_pwd", pwd)
                    if(!TextUtils.isEmpty(bean.session)){
                        SpUtils.put("module_session", bean.session)
                    }
                    SpUtils.put("module_nickName",name)
                    MyApplication.session = bean.session
                    toLogin(email,pwd)
                } else {
                    Toast.makeText(this@RegisterActivity, "注册失败", Toast.LENGTH_SHORT)
                        .show()
                }
            }

            override fun onError(call: Call?, response: Response?, e: Exception?) {
                llModule.visibility = View.GONE
                LogUtil.e("注册失败 ${GsonUtils.toJson(e!!.message.toString())}")
            }
        })

    }


    fun toLogin(email: String, pwd: String) {
        HTTPAPI.toLogin(email, pwd, object : StringCallback() {
            override fun onSuccess(t: String?, call: Call?, response: Response?) {
                LogUtil.e("登录结果$t")
                var bean: LoginCallbackBean =
                    GsonUtils.parse(t.toString(), LoginCallbackBean::class.java)
                if (!bean.IsError) {
                    if (!TextUtils.isEmpty(bean.session)) {

                    }
                    if(!TextUtils.isEmpty(bean.session)){
                        SpUtils.put("module_session", bean.session)
                    }
                    SpUtils.put("module_uid", bean.uid)
                    SpUtils.put("module_nickName",bean.username)
                    startActivity(Intent(this@RegisterActivity, MainActivity().javaClass))
                    finish()
                } else {
                    Toast.makeText(this@RegisterActivity, bean.ErrorMessage, Toast.LENGTH_SHORT).show()
                }
            }

            override fun onError(call: Call?, response: Response?, e: Exception?) {
                LogUtil.e("登录失败 ${GsonUtils.to(e)}")
                Toast.makeText(this@RegisterActivity,"登录失败-->"+ GsonUtils.to(e),Toast.LENGTH_SHORT).show()
            }
        })
    }
}